package com.itheima.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter(filterName = "loginCheckFilter",urlPatterns = "/*")
public class LoginCheckFilter implements Filter {

    public static final AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //转换
        HttpServletRequest request = (HttpServletRequest)servletRequest;
        HttpServletResponse response = (HttpServletResponse)servletResponse;

        //设置放行路径
        String[] urls = {
                "/backend/**","/front/**","/employee/login","/employee/logout"
        };

        //获取请求路径
        String uri = request.getRequestURI();

        //获取操作者id
        BaseContext.setId((Long) request.getSession().getAttribute("employee"));

        //判断是否匹配，匹配放行
        boolean check = check(urls, uri);
        if (check){
            filterChain.doFilter(request,response);
            return;
        }

        //不匹配查看是否登录，登录放行
        if (request.getSession().getAttribute("employee")!=null){
            filterChain.doFilter(request,response);
            return;
        }


        //未登录返回指定错误信息
        String error = JSON.toJSONString(R.error("NOTLOGIN"));
        response.getWriter().write(error);
    }

    /**
     * 查询路径是否匹配
     * @param urls
     * @param uri
     * @return
     */
    public boolean check(String[] urls,String uri){
        //遍历设置的路径
        for (String url : urls) {
            //判断是否匹配，返回
            if (antPathMatcher.match(url,uri)){
                return true;
            }
        }
        return false;
    }
}
